import api from './apiHelper.js'
import {
	netConfig
} from '../config/netconfig.js';
//https://uniapp.dcloud.net.cn/component/image.html#

Date.prototype.format = function (fmt) {
	var o = {
		"M+": this.getMonth() + 1, //月份 
		"d+": this.getDate(), //日 
		"h+": this.getHours(), //小时 
		"m+": this.getMinutes(), //分 
		"s+": this.getSeconds(), //秒 
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度 
		"S": this.getMilliseconds() //毫秒 
	};
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	}
	for (var k in o) {
		if (new RegExp("(" + k + ")").test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k])
				.length)));
		}
	}
	return fmt;
}

const checkCaches = (str) => {
	if (str == undefined || str == null || str == "")
		return false;
	var key = str.toLower();
	return !!helper.caches[key];
}
/**
 * api帮助
 */
let helper = {
	toast(msg, dur) {
		dur = dur || 2000;
		uni.showToast({
			icon: 'none',
			title: msg,
			duration: dur
		});
	},
	getphone: async (code) => {
		if (code == undefined) {
			uni.showToast({
				icon: 'error',
				title: '授权失败!',
				duration: 2000
			});
			return "";

		}
		let result = await api.get('weixin/phone', {
			code: code
		});
		if (result.code != -1) {
			return result.data;
		}
		return "";
	},
	/**
	 * 获取微信code
	 * @returns code
	 */
	getAccessToken: async () => {
		let result = await api.get('weixin/wx-token', {});
		if (result.code == -1) {
			return "";
		}

		return result.data;
	},
	wxlogin: () => {
		return new Promise((resolve, reject) => {
			//https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html#%E8%B0%83%E7%94%A8%E7%A4%BA%E4%BE%8B
			uni.login({
				provider: "weixin",
				success: (res) => {
					resolve(res.code);
				},
				fail: (err) => {
					reject(err)
				}
			});
		})
	},
	
	toApiUrl: (url) => {
	        return netConfig.baseURL + url;
	    },
	/**
	 * 打开pdf文件
	 * @param {文件} md5 
	 */
	openFile: (md5) => {
		let token = uni.getStorageSync('ACCESSTOKEN');
		uni.request({
			url: netConfig.baseURL + 'file/download?md5=' + md5,
			method: "post",
			header: {
				"content-type": "application/json",
				"Authorization": netConfig.tokenPrefix + " " + token,
			},
			responseType: 'arraybuffer',
			success: (res) => {
				var fs = uni.getFileSystemManager();
				var path = `${wx.env.USER_DATA_PATH}/${md5}.pdf`;
				const file = fs.writeFileSync(
					path,
					res.data,
					'utf8'
				);
				console.warn(file);
				uni.openDocument({
					filePath: path,
					showMenu: true,
					success: function (res) {
						console.log('打开文档成功');
					}
				});
			},
			fail: (err) => {
				helper.toast(err.errMsg);
				reject(err)
			}
		});
	},
	/**
	 * 打开pdf文件无需授权
	 * @param {文件MD5} md5 
	 */
	openFile2: (md5) => {
		let token = uni.getStorageSync('ACCESSTOKEN');
		uni.request({
			url: netConfig.baseURL + 'file/download2?md5=' + md5,
			method: "get",
			header: {
				"content-type": "application/json",
			},
			responseType: 'arraybuffer',
			success: (res) => {
				var fs = uni.getFileSystemManager();
				var path = `${wx.env.USER_DATA_PATH}/${md5}.pdf`;
				const file = fs.writeFileSync(
					path,
					res.data,
					'utf8'
				);
				console.warn(file);
				uni.openDocument({
					filePath: path,
					showMenu: true,
					success: function (res) {
						console.log('打开文档成功');
					}
				});
			},
			fail: (err) => {
				helper.toast(err.errMsg);
				reject(err)
			}
		});
	},
	savevideo(path) {
		uni.saveVideoToPhotosAlbum({
			filePath: path,
			success: function () {
				console.log('save success');
				uni.showToast({
					title: "下载成功"
				})
			},
			error: function (res) {

				uni.showToast({
					title: res
				})
			}
		});
	},
	/**
	 * 下载视频文件
	 * @param {文件} md5 
	 */
	downloadMediaFile: (md5) => {
		let token = uni.getStorageSync('ACCESSTOKEN');
		uni.showLoading({
			icon: "none",
			title: "下载中..."
		})
		uni.request({
			url: netConfig.baseURL + 'file/download?md5=' + md5,
			method: "post",
			header: {
				"content-type": "application/json",
				"Authorization": netConfig.tokenPrefix + " " + token,
			},
			responseType: 'arraybuffer',
			success: (res) => {
				uni.hideLoading()
				var fs = uni.getFileSystemManager();
				var path = `${wx.env.USER_DATA_PATH}/${md5}.mp4`;
				const file = fs.writeFileSync(
					path,
					res.data,
					'utf8'
				);
				uni.authorize({
					scope: 'scope.writePhotosAlbum',
					success() {
						// 用户已授权，可以保存视频
						helper.savevideo(path)
					},
					fail() {
						// 用户拒绝授权，引导用户开启
						uni.showModal({
							title: '提示',
							content: '此功能需要保存视频到相册权限，请设置打开权限',
							success: function (modalRes) {
								if (modalRes.confirm) {
									uni.openSetting({
										success: function (settingRes) {
											if (settingRes.authSetting['scope.writePhotosAlbum']) {
												// 用户在设置页打开了授权
												helper.savevideo(path)
											}
										}
									});
								}
							}
						});
					}
				});


			},
			fail: (err) => {
				uni.hideLoading()
				helper.toast(err.errMsg);
				reject(err)
			},
			complete() {

			}
		});
	},

	/**
	 * 照片选择 或 相机拍摄
	 * @returns 文件路径
	 */
	chooseImage: () => {
		return new Promise((resolve, reject) => {
			uni.chooseImage({
				count: 1, //最多可以选择的图片张数，默认9
				//sourceType: ['album'], //album 从相册选图，camera 使用相机，默认二者都有。如需直接开相机或直接选相册，请只使用一个选项
				sizeType: ["compressed"], //original 原图，compressed 压缩图，默认二者都有
				success(res) {
					console.log("选择图片完成", res);
					resolve(res.tempFilePaths[0]);
				},
				fail(err) {
					reject(err);
					console.log("失败", err);
				},
				complete() {
					console.log("结束");
				},
			});
		});
	},
	/**
	 * 照片选择 或 相机拍摄(多文件)
	 * @returns 文件路径
	 */
	chooseImageMore: () => {
		return new Promise((resolve, reject) => {
			uni.chooseImage({
				count: 9, //最多可以选择的图片张数，默认9
				//sourceType: ['album'], //album 从相册选图，camera 使用相机，默认二者都有。如需直接开相机或直接选相册，请只使用一个选项
				sizeType: ["compressed"], //original 原图，compressed 压缩图，默认二者都有
				success(res) {
					console.log("选择图片完成", res);
					resolve(res.tempFilePaths);
				},
				fail(err) {
					reject(err);
					console.log("失败", err);
				},
				complete() {
					console.log("结束");
				},
			});
		});
	},
	/**
	 * 视频选择 或 相机拍摄
	 * @returns 文件路径
	 */
	chooseVideo: () => {
		return new Promise((resolve, reject) => {
			uni.chooseMedia({
				mediaType: ['video'],
				count: 1,
				sizeType: ["compressed"],
				maxDuration: 10,
				//sourceType: ['camera'],
				success: function (res) {

					resolve(res.tempFiles[0]);


				},
				fail(err) {

					reject(err);
					console.log("失败", err);
				},
				complete() {

					console.log("结束");
				},
			});

		})

	},
	/**
	 * 上传文件
	 * @param {文件路径} url 
	 * @returns md5
	 */
	uploadFile: (url,filename) => {
		return new Promise((resolve, reject) => {
			let token = uni.getStorageSync('ACCESSTOKEN');
			
			uni.uploadFile({
				header: {
					"Authorization": netConfig.tokenPrefix + " " + token,
				},
				url: netConfig.baseURL + 'weixin/file-upload',
				filePath: url,
				name: filename?filename:'file',
				success: (res) => {
					resolve(JSON.parse(res.data).data);
				},
				fail: (err) => {
					reject(err);
				}
			});
		})
	},
	/**
	 * 获取当前用户
	 * @returns OpenID
	 */
	getOpenId: async () => {
		
		var openid = uni.getStorageSync('OPENID');
		if (openid) {
			return openid;
		}
		let code = await helper.wxlogin();
		let result = await api.get('weixin/openid', {
			code: code
		});
		openid = result.data;
		uni.setStorageSync('OPENID', openid);
		return openid;
	},
	/**
	 * 图片预览地址
	 * @param {文件MD5} md5 
	 */
	getImageUrl: (md5) => {
		if (md5 == "" || md5 == undefined) return "";
		return netConfig.baseURL + 'file/download2?md5=' + md5;
	},
	/**
	 * 是否注册用户
	 * @returns bool
	 */
	checkUser: async () => {

		var reg = uni.getStorageSync('REGISTER');
		if (reg != "") {
			return true;
		}
		var openid = await helper.getOpenId();
		let result = await api.post('account/check-user/' + openid);
		if (result.code != -1 && result.data) {
			uni.setStorageSync('REGISTER', true);
		}
		return result.data;
	},
	/**
	 * 是否会员用户
	 * @returns bool
	 */
	checkMember: async () => {
		var openid = await helper.getOpenId();
		let result = await api.post('user/check-member/' + openid);
		return result.data;
	},
	/**
	 * TOKEN是否过期
	 * @returns bool
	 */
	checkAuthorized: () => {
		let token = uni.getStorageSync('ACCESSTOKEN');
		return token != "";
	},
	/**
	 * 本地图片转换为base64
	 * 例如 http://temp/xxx.jpg
	 */
	url2Base64: async (url) => {
		var result = await helper.uploadFile(url);
		return result;
	},
	/**
	 * 当前用户
	 * @returns 头像
	 */
	getIcon: async () => {
		let openid = await helper.getOpenId();
		return netConfig.baseURL + 'weixin/icon/' + openid;
	},
	/**
	 * 指定用户
	 * @param {用户ID} openid 
	 * @returns 头像
	 */
	getIcon2: async (openid) => {
		return netConfig.baseURL + 'weixin/icon/' + openid;
	},
	getUser: async () => {
		let user = uni.getStorageSync('USER');
		if (user == "") {
			let openid = await helper.getOpenId();
			var result = await api.get('customer/customer/' + openid);
			if (result.code != -1) {
				uni.setStorageSync('USER', user);
				user = result.data;
			}
		}
		return user;
	},
	// 将日期格式化为 年.月.日 的形式
	formatDate: (dateString) => {
		const date = new Date(dateString);
		return date.format("yyyy.MM.dd");
	},

	// 将日期格式化为 年.月 的形式
	getYearMonth: (dateString) => {
		const date = new Date(dateString);
		return date.format("yyyy.MM");
	},
	/**
	 * source转换为destination
	 * @param {JSON} source 
	 * @param {JSON} destination 
	 */
	mapper: (source, destination) => {
		Object.keys(destination).map(function (key) {
			source[key] && (destination[key] = source[key]);
		})
	},
	getDic: async (group) => {
		let dics = uni.getStorageSync('DIC');
		if (dics == "") {
			var result = await api.get('appinfo/dic', {});
			dics = result.data;
			uni.setStorageSync('DIC', dics);
		}

		var list = new Array();
		for (var i = 0; i < dics.length; i++) {
			if (dics[i].group.toUpperCase() == group.toUpperCase()) {
				list.push(dics[i]);
			}
		}
		return list;
	},
	Now: () => {
		var date = new Date();
		return date.format("yyyy-MM-dd");
	},
	setEmpower: (() => {
		uni.setStorageSync('EMPOWER', "true");
	}),
	clearEmpower: (() => {
		uni.setStorageSync('EMPOWER', "");
	}),
	isEmpower: () => uni.getStorageSync('EMPOWER') == "true",
	isDev: process.env.NODE_ENV === 'development',
	toDate: (date, format) => {
		return new Date(date.replace(/-/g, "/")).format(format)
	},
	caches: {
		token: "TOKEN",
		user: "USER"
	},
	/**
	 * 获取缓存
	 * @param {键} caches.key 
	 * @returns 
	 */
	getCache: (key) => {
		if(!checkCaches(key))
			return undefined;
		let value = uni.getStorageSync(key);
		return value;
	},
	/**
	 * 删除缓存
	 * @param {键} caches.key 
	 * @param {值} value 
	 */
	setCache: (key, value) => {
		if(!checkCaches(key))
			return ;
		uni.setStorageSync(key, value);
	},
	/**
	 * 清除缓存
	 * @param {键} caches.key
	 */
	clearCache: (key) => {
		if(!checkCaches(key))
			return ;
		uni.setStorageSync(key, '');
	},
	/**
	 * 播打电话
	 * @param {号码} number 
	 */
	call: async (number) => {
		uni.makePhoneCall({
			phoneNumber: number
		})
	},
	/**
	 * 消息订阅授权
	 * https://developers.weixin.qq.com/miniprogram/dev/api/open-api/subscribe-message/wx.requestSubscribeMessage.html
	 */
	questEmpower() {
		//#ifdef MP-WEIXIN
		wx.requestSubscribeMessage({
			tmplIds: ['KU4gaffTla_5OnlFUwSEFAzb5hFPmqivxNXh6qsXNzw'],
			success(res) {
				
				if (res['KU4gaffTla_5OnlFUwSEFAzb5hFPmqivxNXh6qsXNzw'] == "reject") {
					helper.toast("请在右上，更多->点击设置->订阅消息->接收", 5000);
					return;
				}
				helper.setEmpower();
				console.log(res);
			},
			fail(er) {
				
				helper.toast("请在右上角，更多->点击设置->订阅消息", 5000);
				helper.clearEmpower();
				console.log(er);
			}
		})
		//#endif
	},
	 buildTree(newdata, parentId){
	  const tree = [];
	  // 遍历数据
	  newdata.forEach((item) => {
	    // 如果当前节点的 parentId 与父节点的 id 相等，说明是父节点的子节点
	    if (item.parentId === parentId) {
	      // 使用递归调用，将子节点也转换为树形结构
	      const children = this.buildTree(newdata, item.id);
			
	      // 如果子节点存在，则将子节点添加到当前节点的 children 属性中
	      if (children.length > 0) {
	        item.children = children;
			item.user=false
	      }else{
			  item.user=true
		  }
	
	      // 将当前节点添加到树中
	      tree.push(item);
	    }
	  });
	
	  return tree;
	},
	defaultLogo: 'https://api.daka-cn.com/image/avatar.svg'
}
export default helper;